<template>
  <div class="law-list">
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="法律代码">
          <el-input
            v-model="searchForm.lawCode"
            placeholder="请输入法律代码"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="条款内容">
          <el-input
            v-model="searchForm.content"
            placeholder="请输入条款内容"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="关联分类">
          <el-cascader
            v-model="searchForm.categoryId"
            :options="categoryTree"
            :props="{ value: 'id', label: 'name', children: 'children', emitPath: false }"
            placeholder="请选择分类"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="生效日期">
          <el-date-picker
            v-model="searchForm.effectiveDateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 350px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作区域 -->
    <div class="action-section">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增条款
      </el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="lawCode" label="法律代码" width="150" />
        <el-table-column prop="content" label="条款内容" min-width="300" show-overflow-tooltip />
        <el-table-column prop="effectiveDate" label="生效日期" width="180" />
        <el-table-column prop="documentTitle" label="关联文档" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.documentTitle" class="document-link">{{ row.documentTitle }}</span>
            <span v-else class="no-document">暂无关联</span>
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" label="关联分类" width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tag v-if="row.categoryName" type="info" size="small">
              {{ row.categoryName }}
            </el-tag>
            <span v-else class="no-category">暂无分类</span>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleDetail(row)"
            >
              详情
            </el-button>
            <el-button
              type="success"
              size="small"
              :loading="editLoadingMap[row.id]"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.pageNum"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <LawForm
      v-model:visible="formVisible"
      :law-data="currentLaw"
      @refresh="fetchLawList"
    />

    <!-- 详情对话框 -->
    <LawDetail
      v-model:visible="detailVisible"
      :law-id="currentLawId"
      @edit="handleEdit"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { getLawPage, deleteLaw, getLawDetail } from '../../api/law'
import { getCategoryList } from '../../api/category'
import LawForm from './components/LawForm.vue'
import LawDetail from './components/LawDetail.vue'

// 搜索表单
const searchForm = reactive({
  lawCode: '',
  content: '',
  categoryId: null,
  effectiveDateRange: null
})

// 分页信息
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 编辑按钮加载状态
const editLoadingMap = ref({})

// 对话框状态
const formVisible = ref(false)
const detailVisible = ref(false)
const currentLaw = ref(null)
const currentLawId = ref(null)

// 分类树数据
const categoryTree = ref([])

// 构建分类树
const buildCategoryTree = (categories) => {
  const tree = []
  const map = new Map()
  
  // 先创建所有节点的映射
  categories.forEach(category => {
    map.set(category.id, { 
      ...category, 
      children: [] 
    })
  })
  
  // 构建树形结构
  categories.forEach(category => {
    const node = map.get(category.id)
    if (category.parentId === 0) {
      // 顶级分类
      tree.push(node)
    } else {
      // 子分类
      const parent = map.get(category.parentId)
      if (parent) {
        parent.children.push(node)
      }
    }
  })
  
  return tree
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const response = await getCategoryList()
    if (response.code === 200) {
      categoryTree.value = buildCategoryTree(response.data)
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 获取法律条款列表
const fetchLawList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    
    // 处理日期范围
    if (searchForm.effectiveDateRange && searchForm.effectiveDateRange.length === 2) {
      params.effectiveStartDate = searchForm.effectiveDateRange[0]
      params.effectiveEndDate = searchForm.effectiveDateRange[1]
    }
    delete params.effectiveDateRange
    
    // 过滤空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await getLawPage(params)
    if (response.code === 200) {
      tableData.value = response.data.records
      pagination.total = response.data.total
    }
  } catch (error) {
    console.error('获取法律条款列表失败:', error)
    ElMessage.error('获取法律条款列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.pageNum = 1
  fetchLawList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    lawCode: '',
    content: '',
    categoryId: null,
    effectiveDateRange: null
  })
  pagination.pageNum = 1
  fetchLawList()
}

// 新增
const handleAdd = () => {
  currentLaw.value = null
  formVisible.value = true
}

// 编辑
const handleEdit = async (row) => {
  editLoadingMap.value[row.id] = true
  try {
    const response = await getLawDetail(row.id)
    if (response.code === 200) {
      currentLaw.value = response.data
      formVisible.value = true
    }
  } catch (error) {
    console.error('获取法律条款详情失败:', error)
    ElMessage.error('获取法律条款详情失败')
  } finally {
    editLoadingMap.value[row.id] = false
  }
}

// 详情
const handleDetail = (row) => {
  currentLawId.value = row.id
  detailVisible.value = true
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除法律条款"${row.lawCode}"吗？`,
      '确认删除',
      {
        type: 'warning'
      }
    )

    const response = await deleteLaw(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchLawList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除法律条款失败:', error)
      ElMessage.error('删除法律条款失败')
    }
  }
}

// 分页大小改变
const handleSizeChange = () => {
  pagination.pageNum = 1
  fetchLawList()
}

// 当前页改变
const handleCurrentChange = () => {
  fetchLawList()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCategories()
  fetchLawList()
})
</script>

<style scoped>
.law-list {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.search-form {
  margin: 0;
}

.action-section {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-section {
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: center;
}

.document-link {
  color: #409EFF;
  cursor: pointer;
}

.document-link:hover {
  text-decoration: underline;
}

.no-document,
.no-category {
  color: #999;
  font-style: italic;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .law-list {
    padding: 10px;
  }
  
  .search-form {
    display: block;
  }
  
  .search-form .el-form-item {
    width: 100%;
    margin-bottom: 10px;
  }
  
  .search-form .el-input,
  .search-form .el-cascader,
  .search-form .el-date-picker {
    width: 100% !important;
  }
}
</style>
